package com.hntky.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hntky.common.Result;
import com.hntky.entity.Patient;
import com.hntky.entity.Sickroom;
import com.hntky.exception.ServiceException;
import com.hntky.service.PatientService;
import com.hntky.service.SickroomService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 周宇轩
 * @date 2023/5/14 15:06
 */
@RestController
@RequestMapping("/patient")
public class PatientController {

    @Resource
    private PatientService service;

    @Resource
    private SickroomService sickroomService;

    /**
     * 分页查询和搜索
     * @param pageNum
     * @param pageSize
     * @param pname
     * @return
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String pname) {
        return Result.success(service.findPage(new Page<>(pageNum, pageSize), pname));

    }

    /**
     * 新增和修改
     * @param patient
     * @return
     */
    @PostMapping("/add/{sid}")
    public Result add(@RequestBody Patient patient, @PathVariable Integer sid) {
        // 修改和新增病人信息之前查询该病房的床位是否充足
        QueryWrapper<Sickroom> queryWrapper = new QueryWrapper();
        queryWrapper.eq("sid", patient.getSickroomid());
        // 查询病人要入住的病房
        Sickroom toRoom = sickroomService.getOne(queryWrapper);
        if(toRoom.getSnum() <= 0) {
            // 床位不足
            throw new ServiceException("500", "床位不足");
        }
        // 查看病人退出的病房
        QueryWrapper<Sickroom> queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("sid", sid);
        Sickroom outRoom = sickroomService.getOne(queryWrapper1);
        // 床位充足
        toRoom.setSnum( toRoom.getSnum() - 1 );
        outRoom.setSnum( outRoom.getSnum() + 1);
        // 更新床位
        boolean a = sickroomService.updateById(toRoom);
        boolean b = sickroomService.updateById(outRoom);
        if( a != true && b != true) {
            throw new ServiceException("500", "保存失败");
        }
        return Result.success(service.saveOrUpdate(patient));
    }

    /**
     * 修改病人状态
     * @param patient
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Patient patient) {
        return Result.success(service.updateById(patient));
    }

    /**
     * 根据id删除
     * @param pid
     * @return
     */
    @GetMapping("/{pid}")
    public Result del(@PathVariable Integer pid) {
        return Result.success(service.removeById(pid));
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    public Result delBatch(@RequestBody List<Integer> ids) {
        return Result.success(service.removeBatchByIds(ids));
    }
}
